import time
import uuid
from flask import Flask, request, Blueprint
from flask_cors import CORS
from extensions.rpcApi import *
from extensions import MonConn
from extensions.utils import *
app = Flask(__name__)
CORS(app)
api_bp = Blueprint('api', __name__, url_prefix='/api')


def generate_uuid_with_time():
    current_time = int(time.time() * 1000)  # 获取当前时间戳（毫秒）
    unique_id = uuid.uuid1(node=current_time)  # 使用时间戳作为节点值生成 UUID
    return str(unique_id)


@api_bp.route('/rpc/run', methods=['POST'])
def run():
    query_data = request.json
    url = query_data.get("url")
    task_id = generate_uuid_with_time()
    rpc_run(url=url, task_id=task_id)
    return {"status": True, "msg": "任务运行成功", "task_id": task_id}


@api_bp.route('/rpc/stop', methods=['POST'])
def stop():
    form_data = request.form.to_dict()
    pid = form_data.get("pid")
    rpc_stop(pid)
    return {"status": True, "msg": "任务停止成功", "pid": pid}


@api_bp.route('/rpc/task', methods=['GET', 'POST'])
def RPC_task():
    query_data = request.json
    print(query_data)
    status = query_data.get("status")
    task_id = query_data.get("task_id")
    condition = {"task_id": task_id}
    condition = {"status": status} if status else condition
    query_list = MonConn.findall('RpcSpider', condition)
    query_list = foomatMid(query_list)
    return {"status": True, "msg": "Rpc任务列表", "data": query_list}


@api_bp.route('/')
def homt():
    return 'Welcome to my api'


app.register_blueprint(api_bp)

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8008, debug=True)
